<template>
  <div style="padding-top: 5px">
    <el-row :gutter="10">
      <el-col :md="12" :sm="24">
        <el-card :bordered="false">
          <!-- 按钮操作区域  @click="handleAdd()"  @click="batchDel" @click="refresh" -->
          <el-row style="margin-left: 14px">
            <el-button @click="handleAdd()" type="primary">添加类别</el-button>
            <el-button title="删除多条数据"  @click="batchDel"  type="default">批量删除</el-button>
            <el-button @click="refresh" type="default" icon="reload">刷新</el-button>
          </el-row>
          <div style="background: #fff;padding-left:16px;height: 100%; margin-top: 5px">
          <el-alert type="info" :showIcon="true">
            
              当前选择：<span v-if="this.currSelected.title">{{ this.currSelected.title }}</span>
              <a v-if="this.currSelected.title" style="margin-left: 10px;color: #409EFF;" @click="onClearSelected">取消选择</a>
            
          </el-alert>
          <el-col :md="10" :sm="24">
              <el-tree
              :data="optionsTree"
              show-checkbox
              default-expand-all
              node-key="id"
              ref="tree"
              highlight-current
              @node-click = "handleNodeClick"
              :expand-on-click-node = "false"
              :props="defaultProps">
            </el-tree>
          </el-col>
        </div>
        </el-card> 
        <div class="drawer-bootom-button">
            <el-dropdown>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item key="1" divided  @click.native="checkALL">全部勾选</el-dropdown-item>
                <el-dropdown-item key="2" @click.native="inverse">取消全选</el-dropdown-item>
                <el-dropdown-item key="3" divided  @click.native="expandAll">展开所有</el-dropdown-item>
                <el-dropdown-item key="4" @click.native="closeAll">合并所有</el-dropdown-item>
              </el-dropdown-menu>
              <el-button class="el-dropdown-link">
                树操作 <el-icon type="up" />
              </el-button>
            </el-dropdown>
        </div>
      </el-col>
      <el-col :md="12" :sm="24">
        <el-card :bordered="false"  v-if="nodeTreeKey != undefined" >
            <el-form ref="form" :model="form" :rules="rules" label-width="150px">
              <el-row>
                <el-col :span="20">
                  <el-form-item label="名称" prop="name">
                    <el-input v-model="form.name"  placeholder="请输入名称" maxlength="30" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item label="编号" prop="serialNo">
                    <el-input v-model="form.serialNo" placeholder="请输入编号" maxlength="30" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item label="上级目录" prop="">
                    <tree-select :options="optionsTree" v-model="form.parentId" :searchable="false"
                      :default-expand-level="Infinity" :open-on-click="true" :open-on-focus="true"
                      :normalizer="normalizer" placeholder="请选择上级目录" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="12">
                  <el-form-item label="排序" prop="sort">
                    <el-input-number v-model="form.sort" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row>
                <el-col :span="20">
                  <el-form-item label="备注" prop="remark">
                    <el-input v-model="form.remark" placeholder="请输入备注" maxlength="30" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-form>
            <div class="anty-form-btn">
              <el-button @click="emptyCurrForm" type="default" htmlType="button" icon="sync">重置</el-button>
              <el-button @click="submitCurrForm" type="primary" htmlType="button" icon="form">保存</el-button>
            </div>
        </el-card>
        <el-card v-else >
          <div  class="ant-col ant-col-sm-24 ant-col-md-12" style="padding-left: 5px; padding-right: 5px;"><div data-v-d39f7178="" class="ant-card ant-card-bordered"><div class="ant-card-body"><div data-v-d39f7178="" class="ant-empty"><div class="ant-empty-image"><svg width="184" height="152" viewBox="0 0 184 152" xmlns="http://www.w3.org/2000/svg"><g fill="none" fillRule="evenodd"><g transform="translate(24 31.67)"><ellipse fillOpacity=".8" fill="#F5F5F7" cx="67.797" cy="106.89" rx="67.797" ry="12.668"></ellipse><path d="M122.034 69.674L98.109 40.229c-1.148-1.386-2.826-2.225-4.593-2.225h-51.44c-1.766 0-3.444.839-4.592 2.225L13.56 69.674v15.383h108.475V69.674z" fill="#AEB8C2"></path><path d="M101.537 86.214L80.63 61.102c-1.001-1.207-2.507-1.867-4.048-1.867H31.724c-1.54 0-3.047.66-4.048 1.867L6.769 86.214v13.792h94.768V86.214z" fill="url(#linearGradient-1)" transform="translate(13.56)"></path><path d="M33.83 0h67.933a4 4 0 0 1 4 4v93.344a4 4 0 0 1-4 4H33.83a4 4 0 0 1-4-4V4a4 4 0 0 1 4-4z" fill="#F5F5F7"></path><path d="M42.678 9.953h50.237a2 2 0 0 1 2 2V36.91a2 2 0 0 1-2 2H42.678a2 2 0 0 1-2-2V11.953a2 2 0 0 1 2-2zM42.94 49.767h49.713a2.262 2.262 0 1 1 0 4.524H42.94a2.262 2.262 0 0 1 0-4.524zM42.94 61.53h49.713a2.262 2.262 0 1 1 0 4.525H42.94a2.262 2.262 0 0 1 0-4.525zM121.813 105.032c-.775 3.071-3.497 5.36-6.735 5.36H20.515c-3.238 0-5.96-2.29-6.734-5.36a7.309 7.309 0 0 1-.222-1.79V69.675h26.318c2.907 0 5.25 2.448 5.25 5.42v.04c0 2.971 2.37 5.37 5.277 5.37h34.785c2.907 0 5.277-2.421 5.277-5.393V75.1c0-2.972 2.343-5.426 5.25-5.426h26.318v33.569c0 .617-.077 1.216-.221 1.789z" fill="#DCE0E6"></path></g><path d="M149.121 33.292l-6.83 2.65a1 1 0 0 1-1.317-1.23l1.937-6.207c-2.589-2.944-4.109-6.534-4.109-10.408C138.802 8.102 148.92 0 161.402 0 173.881 0 184 8.102 184 18.097c0 9.995-10.118 18.097-22.599 18.097-4.528 0-8.744-1.066-12.28-2.902z" fill="#DCE0E6"></path><g transform="translate(149.65 15.383)" fill="#FFF"><ellipse cx="20.654" cy="3.167" rx="2.849" ry="2.815"></ellipse><path d="M5.698 5.63H0L2.898.704zM9.259.704h4.985V5.63H9.259z"></path></g></g></svg></div><p class="ant-empty-description"><span data-v-d39f7178=""> 请先选择一个类别! </span></p></div></div></div></div>
        </el-card>
      </el-col>
       <material-category-module  v-bind:upload="upload"  ref="materialCategoryModule"></material-category-module>
    </el-row>
    <el-dialog
      title="确认删除"
      :visible.sync="dialogVisible"
      width="30%">
      <span>确定要删除所选中的{{ removeIdsLength }}条数据，以及子节点数据吗?</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmBatchDelete">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import TreeSelect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import MaterialCategoryModule from "@/components/material/category/index";
import {
  listCategory,
  checkCategory,
  delCategory,
  addCategory,
  updateCategory,
  getMaterialCategory
} from "@/api/material/category";
export default {
  name: "MaterialCategoryIndex",
  components: {
    MaterialCategoryModule,
    TreeSelect
  },
  data() {
    return {
      // 用户导入参数
      upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
      },
      optionsTree: [],
      currSelected: {},
      dialogVisible: false,
      nodeTreeKey: undefined,
      form: {},
      normalizer(node){
        if(node.children && !node.children.length){
          delete node.children
        }
        return {
          id: node.id,
          label: node.name,
          children: node.children,
        }
      },
      // 表单校验
      rules: {
        name: [
          { required: true, message: "名称不能为空", trigger: "blur" },
          { min: 2, max: 30, message: '长度在 2 到 30 个字符', trigger: 'blur' },
          { validator: this.validateAccountName}
        ],
        serialNo: [
          { required: true, message: "编号不能为空", trigger: "blur" }
        ]
      },
      checkedKeys:"",
      removeIdsLength: 0,
      defaultProps: {
        children: "children",
        label: "name"
      }
    }
  },
  created(){
    this.loadTree();
  },
  methods: {
    onClearSelected(){
      this.nodeTreeKey = undefined;
      this.currSelected = {};
    },
    handleNodeClick(node){
      this.nodeTreeKey = node.id;
      console.log(this.nodeTreeKey)
      this.currSelected.title = node.name;
      getMaterialCategory(node.id).then(response => {
        this.form = response.data;
      });
    },
    loadTree(){
      listCategory(0).then(response => {
        this.optionsTree = response.data;
      })    
    },
    inverse(){
      let res = this.$refs.tree;
      let nodes = res.getCheckedNodes(true, true);
      this.batchSelect(this.optionsTree, res, true, nodes);
    },
    // 全选处理方法
    batchSelect(nodes, refs, flag, seleteds) {
      if (typeof nodes != "undefined") {
        nodes.forEach(element => {
          refs.setChecked(element, flag, true);
        });
      }

      if (typeof seleteds != "undefined") {
        seleteds.forEach(node => {
          refs.setChecked(node, !flag, true);
        });
      }
    },
    emptyCurrForm(){
      this.form = {};
    },
    submitCurrForm(){
      this.$refs["form"].validate(valid => {
         if (valid) {
          if (!this.nodeTreeKey) {
            this.$message.warning('请点击选择要修改类别!')
            return
          }
          updateCategory(this.form).then(response => {
            if (response.code == 200) {
                  this.$message.success('保存成功!')
                  this.loadTree()
                } else {
                  this.$message.error(response.message)
                }
          })
        }
      })
      
    },
    checkALL(){
      this.$refs.tree.setCheckedNodes(this.optionsTree); 
    },
    closeAll(){
      this.optionsTree.forEach((el) => {
        this.$refs.tree.store.nodesMap[el.id].expanded = false;
      })
    },
    expandAll(){
      this.optionsTree.forEach((el) => {
        this.$refs.tree.store.nodesMap[el.id].expanded = true;
      });
    },
    handleAdd() {
      this.$refs.materialCategoryModule.loadNodeTree();
      this.upload.title = "新增";
      this.upload.open = true;
    },
    batchDel(){
      let checkedKeys = this.$refs.tree.getCheckedKeys();
      this.checkedKeys = checkedKeys;
       if (checkedKeys.length <= 0) {
          this.$message.warning('请选择一条记录！');
       }else{
         this.removeIdsLength = checkedKeys.length;
          this.dialogVisible = true;
       }
    },
    confirmBatchDelete(){
      var ids = [];
      for (var a = 0; a < this.checkedKeys.length; a++) {
        ids.push(this.checkedKeys[a]);
      }
      delCategory(ids).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg);
          this.loadTree();
          this.nodeTreeKey = undefined;
        } else {
          this.$message.warning(res.msg);
        }
      }).catch(() => {});
       this.dialogVisible = false;
    },
    refresh(){
      this.loadTree();
      this.nodeTreeKey = undefined;
      this.currSelected = {};
    }
  }
}
</script>
<style lang="less">
  .el-alert .el-alert__description {
      font-size: 15px;
      margin: 5px 0 0 0;
      
  }
  .ant-empty {
      margin: 0 8px;
      font-size: 14px;
      line-height: 22px;
      text-align: center;
  }
  .el-dropdown-link {
    cursor: pointer;
    color: #409EFF;
  }
  .el-icon-arrow-down {
    font-size: 12px;
  }
  .drawer-bootom-button {
  /*position: absolute;*/
  bottom: 0;
  width: 100%;
  border-top: 1px solid #e8e8e8;
  padding: 10px 16px;
  text-align: left;
  left: 0;
  background: #fff;
  border-radius: 0 0 2px 2px;
}
#app{
    background: #f6f6f6;
}
</style>

